import Vue from 'vue'
import VueRouter from 'vue-router'
import qs from 'qs'
import store from '../store'
import defaultRouter from './1dashboard'
import {
  removeAllToken,
  VUE_APP_clientId,
  VUE_APP_logoutUri,
  VUE_APP_userAuthorizationUri
} from "@/utils/oAuth2Login";
import {delUrl} from "@/utils/urlParse";
import {getFuncAuthorityBySelfLogin} from "@/api/user";

Vue.use(VueRouter)

const routes = [
    defaultRouter
]


export function login() {
  const redirectUri = delUrl(location.href, ['code', 'state', 'session_state'])
  const param = qs.stringify({
    client_id: VUE_APP_clientId,
    response_type: 'code',
    scope: 'openid',
    state: 1,
    redirect_uri: encodeURI(redirectUri)
  })
  removeAllToken()
  resetRouter()
  location.href = `${VUE_APP_userAuthorizationUri}?${param}`
}


export function logout() {
  const redirectUri = delUrl(location.href, ['code', 'state', 'session_state'])
  const param = qs.stringify({
    id_token_hint: store.state.token,
    client_id: VUE_APP_clientId,
    post_logout_redirect_uri: encodeURI(redirectUri)
  })
  removeAllToken()
  resetRouter()
  location.href = `${VUE_APP_logoutUri}?${param}`
}

const createRouter = ()=>new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})
const router = createRouter()


export function resetRouter() {
  window.flapRoutes = null
  const newRouter = createRouter()
  router.matcher = newRouter.matcher // reset router
}



router.beforeEach(async (to, from, next)=>{
  if (to.query.code && to.query.state) {
    const getToken = await store.dispatch('getJwtToken', to.query.code)
    const tempTo = JSON.parse(JSON.stringify(to))
    delete tempTo.query.code
    delete tempTo.query.state
    delete tempTo.query.session_state
    if (!store.state.token) {
      return false
    }
    if (typeof getToken === 'object') {
      return next({ ...tempTo, 'replace': true })
    } else {
      console.log("token获取失败")
      logout()
      return false
    }
  }
  const hasToken = store.state.token
  if (hasToken) {
    if(window.flapRoutes){ // 判断是否有路由
      console.log('有值')
      next()
    }else{
      getFuncAuthorityBySelfLogin().then(res=>{
        resetRouter()
        if(res.data.code===200){
          const data = res.data.data
          const someRouter = [...data[0].moduleAuthorityDtos]
          store.dispatch('setRouter/generateRoutes',someRouter)
          // router.addRoute(window.flapRoutes)
          next()
        }
      })
    }
  } else {
    // 白名单
     if (to.path.indexOf('/applicationResidence') !== -1) {
      next()
    } else {
      const params = {
        name: 'replaceUrl',
        fullPath: window.location.pathname
      }
      const str = JSON.stringify(params)
      localStorage.setItem('href', str)
     login()
    }
  }
})
export default router
